<?php
class Clbtoiyeu_IndexController extends Zend_Controller_Action
{
    /**
     * Global config
     */
    private $configuration  = null;

    /**
     * Category Config
     */
    private $categoryConfig = null;

    /**
     * User login
     */
    private $viewer         = null;

    /**
     * Schedule open
     */
    private $scheduleOpen   = true;

    /**
     * Init controller
     */
    public function init()
    {
        //Viewer
        $this->viewer   = (object)$this->view->user;

        //Get global config
        $this->configuration  = Fpt_Global::getApplicationIni();
        if ( isset($this->configuration['club']['category']) )
        {
            $this->categoryConfig = $this->configuration['club']['category'];
        }
        else
        {
            $this->categoryConfig = array('none'=>0, 'listteam'=>1, 'eurohistory'=>2);
        }//end if

        //Get param
        $paramGlobal    = $this->getRequest()->getParams();

        //Check schedule open
        $this->scheduleOpen = Util_Date::checkSchedule(24, 0, 0, 24, 4, 2012);

        //Assign to view
        $this->view->assign('categoryConfig', $this->categoryConfig);
        $this->view->assign('configuration', $this->configuration);
        $this->view->assign('viewer', $this->viewer);
        $this->view->assign('paramGlobal', $paramGlobal);
        $this->view->assign('scheduleOpen', $this->scheduleOpen);
    }

    /**
     * Index action
     */
    public function indexAction()
    {
        //Get ClubFavorite instance
        $CFInstance     = ClubFavorite::getInstance();

        //Get hot news
        $arrArticleHot  = $CFInstance->getArticleHot(5);

        //Get list post new
        $arrArticlePost = $CFInstance->getArticleByCategoryAndStatus($this->categoryConfig['none'], 1, 4, 0);

        //Get list euro new api
        $arrEuroNews    = $CFInstance->getEuroNews(4);

        //Get list team expression
        $arrTeamExpression  = $CFInstance->getTeamExpression(1);

        //Get list history euro
        $arrHistoryEuro = $CFInstance->getArticleByCategoryAndStatus($this->categoryConfig['eurohistory'], 1, 5, 0);

        //Assign to view
        $this->view->assign('arrArticleHot', $arrArticleHot);
        $this->view->assign('arrArticlePost', $arrArticlePost);
        $this->view->assign('arrEuroNews', $arrEuroNews);
        $this->view->assign('arrTeamExpression', $arrTeamExpression);
        $this->view->assign('arrHistoryEuro', $arrHistoryEuro);

        //Head script
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/slide_jquery.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.easing.1.3.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.CarouSlide.min.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/home-article.js', 'text/javascript');

        //Check schedule
        if ( !$this->scheduleOpen )
        {
            //Head css
            $this->view->headLink()->appendStylesheet(CSS_URL_CLUB.'/colorbox.css', 'screen');
            $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.colorbox.js', 'text/javascript');
        }//end if

        //Head title
        $this->view->headTitle('CLB Tôi Yêu - Trang Chủ');

        //Head meta data
        $this->view->headMeta()->appendName('description', '“Viết về CLB tôi yêu” là cuộc thi viết về CLB bóng đá bạn yêu thích trên chuyên trang VnExpress, với tổng giá trị giải thưởng lên đến 50 triệu đồng.');
        $this->view->headMeta()->appendName('keywords', 'the thao, cau lac bo, cau lac bo toi yeu, clb toi yeu, toi yeu the thao, cau lac bo toi thich');
    }

    /**
     * List action
     */
    public function listAction()
    {
        //Get ClubFavorite instance
        $CFInstance     = ClubFavorite::getInstance();

        //Set array
        $arrArticleHot  = $arrHistoryEuro   =   $arrTeamExpression  =   $arrArticlePost = array();

        //Get type of list
        $type   = $this->getRequest()->getParam('type');
        switch ( $type )
        {
            case 3: //3 - list hot post
                $categoryId = 3;
                $baseUrl    = $this->view->MakeUrlSite(3, array('page'=>'%d'));
                $titlePage  = "Danh Sách Bài Dự Thi Nổi Bật";
                //Get list post new
                $arrArticlePost = $CFInstance->getArticleByCategoryAndStatus($this->categoryConfig['none'], 1, 5, 0);
                break;
            case $this->categoryConfig['listteam']: //1 - list team
                $categoryId = $this->categoryConfig['listteam'];
                $baseUrl    = $this->view->MakeUrlSite(5, array('page'=>'%d'));
                $titlePage  = "Danh Sách Đội Bóng";
                //Get list history euro
                //$arrHistoryEuro = $CFInstance->getArticleByCategoryAndStatus($this->categoryConfig['eurohistory'], 1, 5, 0);
                //Get hot news
                $arrArticleHot  = $CFInstance->getArticleHot(5);
                //Get list post new
                $arrArticlePost = $CFInstance->getArticleByCategoryAndStatus($this->categoryConfig['none'], 1, 5, 0);
                break;
            case $this->categoryConfig['eurohistory']: //2 - euro history
                $categoryId = $this->categoryConfig['eurohistory'];
                $baseUrl    = $this->view->MakeUrlSite(6, array('page'=>'%d'));
                $titlePage  = "Lịch Sử Euro";
                //Get list team expression
                $arrTeamExpression  = $CFInstance->getTeamExpression(5);
                break;
            case $this->categoryConfig['none']: //0 - list post
            default: //list post
                $categoryId = $this->categoryConfig['none'];
                $baseUrl    = $this->view->MakeUrlSite(2, array('page'=>'%d'));
                $titlePage  = "Danh Sách Bài Dự Thi";
                //Get hot news
                $arrArticleHot  = $CFInstance->getArticleHot(5);
                break;
        }//end switch

        //Set limit, offset, num_link
        $limit  = 10;
        $curentPage     = $this->getRequest()->getParam('page');
        $curentPage     = (is_numeric($curentPage) && $curentPage>0)?$curentPage:1;
        $offset         = ($curentPage-1)*$limit;
        $offset         = ($offset>=0)?$offset:0;
        $num_links      = 5;

        //Set status active
        $status         = 1;

        //Get list
        if ( $type == 3 )
        {
            $arrArticle = $CFInstance->getArticleHot($limit, $offset, true);
            $count      = (!empty($arrArticle['list']) && is_array($arrArticle['list']))?count($arrArticle['list']):0;
        }
        else
        {
            $arrArticle = $CFInstance->getArticleByCategoryAndStatus($categoryId, $status, $limit, $offset);
            $count      = (!empty($arrArticle['list']) && is_array($arrArticle['list']))?count($arrArticle['list']):0;
        }//end if

        //Get paging
        $pagingHTML = '';
        if ( $arrArticle['total'] > $limit )
        {
            $arrOption  = array(
                    'base_url'          => $baseUrl,
                    'total_rows'        => $arrArticle['total'],
                    'per_page'          => $limit,
                    'num_links'         => $num_links,
                    'cur_page'          => $curentPage,
                    'prev_link'         => 'Trang trước',
                    'next_link'         => 'Trang sau',
                    'full_tag_open'     => '<ul>',
                    'full_tag_close'    => '</ul>',
                    'cur_tag_open'      => '<li class="active">',
                    'cur_tag_close'     => '</li>',
                    'prev_tag_open'     => '<li class="first">',
                    'prev_tag_close'    => '</li>',
                    'next_tag_open'     => '<li class="end">',
                    'next_tag_close'    => '</li>',
                    'num_tag_open'      => '<li>',
                    'num_tag_close'     => '</li>'
            );
            $objPaging  = new Util_Pagination($arrOption);
            $pagingHTML = $objPaging->createLinkRewrite();
        }//end if

        //Assign to view
        $this->view->assign('arrArticle', $arrArticle);
        $this->view->assign('pagingHTML', $pagingHTML);
        $this->view->assign('categoryId', $categoryId);
        $this->view->assign('start', ($offset+1));
        $this->view->assign('end', ($offset+$count));
        $this->view->assign('arrArticleHot', $arrArticleHot);
        $this->view->assign('arrHistoryEuro', $arrHistoryEuro);
        $this->view->assign('arrTeamExpression', $arrTeamExpression);
        $this->view->assign('arrArticlePost', $arrArticlePost);

        //Head script
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.idTabs.min.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/slide_jquery.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.easing.1.3.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.CarouSlide.min.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/list-article.js', 'text/javascript');

        //Check schedule
        if ( !$this->scheduleOpen )
        {
            //Head css
            $this->view->headLink()->appendStylesheet(CSS_URL_CLUB.'/colorbox.css', 'screen');
            $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.colorbox.js', 'text/javascript');
        }//end if

        //Head title
        $this->view->headTitle('CLB Tôi Yêu - '.$titlePage);

        //Head meta data
        $this->view->headMeta()->appendName('description', '“Viết về CLB tôi yêu” là cuộc thi viết về CLB bóng đá bạn yêu thích trên chuyên trang VnExpress, với tổng giá trị giải thưởng lên đến 50 triệu đồng.');
        $this->view->headMeta()->appendName('keywords', 'the thao, cau lac bo, cau lac bo toi yeu, clb toi yeu, toi yeu the thao, cau lac bo toi thich');
    }

    /**
     * My post action
     */
    public function mypostAction()
    {
        if ( $this->viewer->userid <= 0 )
        {
            $this->_redirect(BASE_URL_CLUB);
        }//end if

        //Get ClubFavorite instance
        $CFInstance     = ClubFavorite::getInstance();

        //Set limit, offset, num_link
        $limit  = 10;
        $curentPage     = $this->getRequest()->getParam('page');
        $curentPage     = (is_numeric($curentPage) && $curentPage>0)?$curentPage:1;
        $offset         = ($curentPage-1)*$limit;
        $offset         = ($offset>=0)?$offset:0;
        $num_links      = 5;

        //Get list my post
        $arrArticle = $CFInstance->getListMyPost($this->viewer->userid, $limit, $offset);
        $count      = (!empty($arrArticle['list']) && is_array($arrArticle['list']))?count($arrArticle['list']):0;

        //Get paging
        $pagingHTML = '';
        if ( $arrArticle['total'] > $limit )
        {
            $arrOption  = array(
                    'base_url'          => $this->view->MakeUrlSite(4, array('page'=>'%d')),
                    'total_rows'        => $arrArticle['total'],
                    'per_page'          => $limit,
                    'num_links'         => $num_links,
                    'cur_page'          => $curentPage,
                    'prev_link'         => 'Trang trước',
                    'next_link'         => 'Trang sau',
                    'full_tag_open'     => '<ul>',
                    'full_tag_close'    => '</ul>',
                    'cur_tag_open'      => '<li class="active">',
                    'cur_tag_close'     => '</li>',
                    'prev_tag_open'     => '<li class="first">',
                    'prev_tag_close'    => '</li>',
                    'next_tag_open'     => '<li class="end">',
                    'next_tag_close'    => '</li>',
                    'num_tag_open'      => '<li>',
                    'num_tag_close'     => '</li>'
            );
            $objPaging  = new Util_Pagination($arrOption);
            $pagingHTML = $objPaging->createLinkRewrite();
        }//end if

        //Get hot news
        $arrArticleHot  = $CFInstance->getArticleHot(5);

        //Get list post new
        $arrArticlePost = $CFInstance->getArticleByCategoryAndStatus($this->categoryConfig['none'], 1, 5, 0);

        //Assign to view
        $this->view->assign('arrArticle', $arrArticle);
        $this->view->assign('arrArticleHot', $arrArticleHot);
        $this->view->assign('arrArticlePost', $arrArticlePost);
        $this->view->assign('pagingHTML', $pagingHTML);
        $this->view->assign('start', ($offset+1));
        $this->view->assign('end', ($offset+$count));

        //Head script
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.idTabs.min.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/slide_jquery.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.easing.1.3.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.CarouSlide.min.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/list-article.js', 'text/javascript');

        //Check schedule
        if ( !$this->scheduleOpen )
        {
            //Head css
            $this->view->headLink()->appendStylesheet(CSS_URL_CLUB.'/colorbox.css', 'screen');
            $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.colorbox.js', 'text/javascript');
        }//end if

        //Head title
        $this->view->headTitle('CLB Tôi Yêu - Danh Sách Bài Dự Thi Của Tôi');

        //Head meta data
        $this->view->headMeta()->appendName('description', '“Viết về CLB tôi yêu” là cuộc thi viết về CLB bóng đá bạn yêu thích trên chuyên trang VnExpress, với tổng giá trị giải thưởng lên đến 50 triệu đồng.');
        $this->view->headMeta()->appendName('keywords', 'the thao, cau lac bo, cau lac bo toi yeu, clb toi yeu, toi yeu the thao, cau lac bo toi thich');
    }

    /**
     * Detail action
     */
    public function detailAction()
    {
        //Get param
        $arrParam   = $this->getRequest()->getParams();

        //Check param
        if ( !isset($arrParam['id']) || !is_numeric($arrParam['id']) || $arrParam['id']<=0 )
        {
            $this->_redirect($this->view->MakeUrlSite(11, null));
        }//end if

        //Get ClubFavorite instance
        $CFInstance = ClubFavorite::getInstance();

        //Get article's info
        $articleInfo    = $CFInstance->getArticleDetail($arrParam['id']);

        //Check article info
        if ( !isset($articleInfo['articleid']) || !is_numeric($articleInfo['articleid']) || $articleInfo['articleid']<=0 )
        {
            $this->_redirect($this->view->MakeUrlSite(11, null));
        }//end if

        //Check active
        if ( $articleInfo['status'] == 0 )
        {
            $this->_redirect($this->view->MakeUrlSite(11, null));
        }//end if

        //Check owner
        if ( $articleInfo['status']==2 && $articleInfo['userid']!=$this->viewer->userid )
        {
            $this->_redirect($this->view->MakeUrlSite(11, null));
        }//end if

        //Get article's statistic
        $arrStatistic   = $CFInstance->getArticleStatistic($articleInfo['articleid'], true);

        //Set statistic
        $articleInfo['total_comment']   = (isset($arrStatistic['total_comment']) && is_numeric($arrStatistic['total_comment']))?$arrStatistic['total_comment']:0;
        $articleInfo['total_view']      = (isset($arrStatistic['total_view']) && is_numeric($arrStatistic['total_view']))?$arrStatistic['total_view']:0;
        $articleInfo['total_vote']      = (isset($arrStatistic['total_vote']) && is_numeric($arrStatistic['total_vote']))?$arrStatistic['total_vote']:0;

        //Insert page view => success => increase total view in article's info
        if ( $articleInfo['status'] == 1 )
        {
            $params     = array(
                    'userid'    => ($this->viewer->userid>0)?$this->viewer->userid:0,
                    'articleid' => $articleInfo['articleid'],
                    'loginip'   => $_SERVER['REMOTE_ADDR'],
                    'sessionid' => session_id()
            );
            if ( $CFInstance->insertPageView($params) )
            {
                $articleInfo['total_view']  = $articleInfo['total_view']+1;
            }//end if
        }//end if

        //Check permission vote
        $permitVote     = false;
        $isShowVote     = false;
        $permitComment  = false;
        if ( $articleInfo['status'] == 1 )
        {
            $permitComment  = true;
            if ( $articleInfo['categoryid'] == $this->categoryConfig['none'] )
            {
                $isShowVote = true;
                if ( $this->viewer->userid <= 0 )
                {
                    if ( isset($_SESSION['userOpenID']) )
                    {
                        if ( !$CFInstance->checkUserVoteByEmail($articleInfo['articleid'], $_SESSION['userOpenID']['email']) )
                        {
                            $permitVote = true;
                        }//end if
                    }
                    else
                    {
                        $permitVote = true;
                    }//end if
                }
                elseif ( !$CFInstance->checkUserVote($articleInfo['articleid'], $this->viewer->userid) )
                {
                    $permitVote = true;
                }//end if
            }//end if
        }//end if

        //Get hot news
        $arrArticleHot  = $CFInstance->getArticleHot(5);

        //Get list post new
        $arrArticlePost = $CFInstance->getArticleByCategoryAndStatus($this->categoryConfig['none'], 1, 5, 0);

        //Assign to view
        $this->view->assign('articleInfo', $articleInfo);
        $this->view->assign('permitVote', $permitVote);
        $this->view->assign('isShowVote', $isShowVote);
        $this->view->assign('permitComment', $permitComment);
        $this->view->assign('arrArticleHot', $arrArticleHot);
        $this->view->assign('arrArticlePost', $arrArticlePost);

        //CSS, JS for OpenID
        $this->view->headLink()->appendStylesheet(CSS_URL.'/openid.css', 'screen');
        $this->view->headScript()->appendFile(JS_URL.'/openid/openid-jquery.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL.'/openid/openid-en.js', 'text/javascript');
        
        //Head css
        $this->view->headLink()->appendStylesheet(CSS_URL_CLUB.'/colorbox.css', 'screen');

        //Head script
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.idTabs.min.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/slide_jquery.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.easing.1.3.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.CarouSlide.min.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.colorbox.js', 'text/javascript');
        $this->view->headScript()->appendFile($this->configuration['domain']['banbe']['plugins']['static'].'/fo-connect.js', 'text/javascript');
        $this->view->headScript()->appendFile($this->configuration['domain']['banbe']['plugins']['static'].'/social-plugins.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/detail-article.js', 'text/javascript');

        //Head title
        $this->view->headTitle('CLB Tôi Yêu - '.$articleInfo['title']);

        //Head meta data
        $this->view->headMeta()->appendName('description', '“Viết về CLB tôi yêu” là cuộc thi viết về CLB bóng đá bạn yêu thích trên chuyên trang VnExpress, với tổng giá trị giải thưởng lên đến 50 triệu đồng.');
        $this->view->headMeta()->appendName('keywords', 'the thao, cau lac bo, cau lac bo toi yeu, clb toi yeu, toi yeu the thao, cau lac bo toi thich');
    }

    /**
     * Preview action
     */
    public function previewAction()
    {
        //Check schedule open
        if ( !$this->scheduleOpen )
        {
            $this->_redirect(BASE_URL_CLUB);
        }//end if

        //Get session
        $session    = new Zend_Session_Namespace(SESSION_NAMESPACE);

        //Get ClubFavorite instance
        $CFInstance = ClubFavorite::getInstance();

        //Define info
        $articleInfo    = array();

        //Check login
        if ( $this->viewer->userid <= 0 )
        {
            $this->_redirect($this->configuration['app']['fptid'].'/dang-nhap.html?referersp='.$this->view->CurrentUrl());
        }//end if

        //Set error
        $error  = array('code'=>0, 'title'=>'', 'content'=>'', 'db'=>'');

        if ( $this->_request->isPost() )
        {
            //Get param
            $params = $this->getRequest()->getParams();
            if ( isset($params['savepreview']) && $params['savepreview']==1 )
            {
                if ( isset($session->preview['title']) && !empty($session->preview['title']) && isset($session->preview['content']) && !empty($session->preview['content']) && isset($session->preview['image']) )
                {
                    //Set param insert
                    $paramInsert    = array(
                            'userid'        => $this->viewer->userid,
                            'user_type'     => 1,
                            'categoryid'    => $this->categoryConfig['none'],
                            'status'        => 2,
                            'title'         => $session->preview['title'],
                            'content'       => $session->preview['content'],
                            'image'         => $session->preview['image'],
                            'url'           => '',
                            'home'          => '',
                            'award'         => '',
                            'info'          => '',
                            'coachman'      => ''
                    );

                    //Unset
                    unset($session->preview);

                    //Insert
                    $articleId  = $CFInstance->insertArticle($paramInsert);

                    //Redirect detail page
                    if ( $articleId > 0 )
                    {
                        $this->_redirect($this->view->MakeUrlSite(1, array('title'=>$paramInsert['title'], 'id'=>$articleId)));
                    }
                    else
                    {
                        $this->_redirect($this->view->MakeUrlSite(11, null));
                    }//end if
                }
                else
                {
                    //Unset
                    unset($session->preview);
                    $this->_redirect($this->view->MakeUrlSite(11, null));
                }//end if
            }
            elseif ( isset($params['txtTitle']) && !empty($params['txtTitle']) && isset($params['ck_content']) && !empty($params['ck_content']) )
            {
                $params['txtTitle'] = Fpt_String::subFullString($params['txtTitle'], 0, 200);

                //Check data
                if ( empty($params['txtTitle']) )
                {
                    $error['code']      = 1;
                    $error['title']     = "Vui lòng nhập tiêu đề.<br>";
                }//end if
                if ( empty($params['ck_content']) )
                {
                    $error['code']      = 1;
                    $error['content']   = "Vui lòng nhập nội dung.<br>";
                }//end if
                if ( $error['code'] == 0 )
                {
                    if ( isset($session->preview['image']) && !empty($session->preview['image']) )
                    {
                        unlink(dirname(UPLOAD_PATH_CLUB).$session->preview['image']);
                    }//end if

                    //Upload file image
                    $uploaded_file  = new Zend_File_Transfer_Adapter_Http();
                    $uploaded_file->addValidator('FilesSize', false, 2000000);
                    $uploaded_file->addValidator('Extension', false, array('jpg', 'gif', 'png'));

                    //Upload file
                    $thumb      = $CFInstance->uploadFile(0, $_FILES['txtfile']['name'], $uploaded_file, dirname(UPLOAD_PATH_CLUB), UPLOAD_PATH_CLUB.'/');

                    //Set param to session

                    $session->preview['title']      = strip_tags($params['txtTitle']);
                    $session->preview['content']    = $params['ck_content'];
                    if ( !empty($thumb['thumb']) )
                    {
                        $session->preview['image']  = $thumb['thumb'];
                    }
                    else
                    {
                        $session->preview['image']  = '';
                    }//end if
                    $articleInfo    = array(
                            'userid'        => $this->viewer->userid,
                            'user_type'     => 1,
                            'categoryid'    => $this->categoryConfig['none'],
                            'status'        => 2,
                            'title'         => strip_tags($params['txtTitle']),
                            'content'       => $params['ck_content'],
                            'image'         => !empty($thumb['thumb'])?$thumb['thumb']:'',
                            'url'           => '',
                            'creation_time' => time(),
                            'total_view'    => 0,
                            'total_vote'    => 0,
                            'total_comment' => 0
                    );
                }
                else
                {
                    $this->_redirect($this->view->MakeUrlSite(7, null));
                }//end if
            }
            else
            {
                $this->_redirect($this->view->MakeUrlSite(7, null));
            }//end if
        }
        else
        {
            $this->_redirect($this->view->MakeUrlSite(7, null));
        }//end if

        //Get hot news
        $arrArticleHot  = $CFInstance->getArticleHot(5);

        //Get list post new
        $arrArticlePost = $CFInstance->getArticleByCategoryAndStatus($this->categoryConfig['none'], 1, 5, 0);

        //Assign to view
        $this->view->assign('articleInfo', $articleInfo);
        $this->view->assign('arrArticleHot', $arrArticleHot);
        $this->view->assign('arrArticlePost', $arrArticlePost);

        //Head css
        $this->view->headLink()->appendStylesheet(CSS_URL_CLUB.'/colorbox.css', 'screen');

        //Head script
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.idTabs.min.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/slide_jquery.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.easing.1.3.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.CarouSlide.min.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.colorbox.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/preview-article.js', 'text/javascript');

        //Head title
        $this->view->headTitle('CLB Tôi Yêu - Xem Trước');

        //Head meta data
        $this->view->headMeta()->appendName('description', '“Viết về CLB tôi yêu” là cuộc thi viết về CLB bóng đá bạn yêu thích trên chuyên trang VnExpress, với tổng giá trị giải thưởng lên đến 50 triệu đồng.');
        $this->view->headMeta()->appendName('keywords', 'the thao, cau lac bo, cau lac bo toi yeu, clb toi yeu, toi yeu the thao, cau lac bo toi thich');
    }

    /**
     * Post action
     */
    public function postAction()
    {
        //Check schedule open
        if ( !$this->scheduleOpen )
        {
            $this->_redirect(BASE_URL_CLUB);
        }//end if

        //Array post
        $arrPost    = array('title'=>'', 'content'=>'');

        //Get session
        $session    = new Zend_Session_Namespace(SESSION_NAMESPACE);

        //Check session preview
        if ( isset($session->preview) )
        {
            $arrPost['title']   = $session->preview['title'];
            $arrPost['content'] = $session->preview['content'];
            //Remove image
            if ( isset($session->preview['image']) && !empty($session->preview['image']) )
            {
                unlink(dirname(UPLOAD_PATH_CLUB).$session->preview['image']);
            }//end if
            unset($session->preview);
        }//end if

        //Check login
        if ( $this->viewer->userid <= 0 )
        {
            $this->_redirect($this->configuration['app']['fptid'].'/dang-nhap.html?referersp='.$this->view->CurrentUrl());
        }//end if

        //Set error
        $error  = array('code'=>0, 'title'=>'', 'content'=>'', 'db'=>'');

        if ( $this->_request->isPost() )
        {
            //Get param
            $params = $this->getRequest()->getParams();
            $params['txtTitle'] = Fpt_String::subFullString($params['txtTitle'], 0, 200);

            //Check data
            if ( empty($params['txtTitle']) )
            {
                $error['code']      = 1;
                $error['title']     = "Vui lòng nhập tiêu đề.<br>";
            }//end if
            if ( empty($params['ck_content']) )
            {
                $error['code']      = 1;
                $error['content']   = "Vui lòng nhập nội dung.<br>";
            }//end if
            if ( $error['code'] == 0 )
            {
                //Get ClubFavorite instance
                $CFInstance = ClubFavorite::getInstance();

                //Upload file image
                $uploaded_file  = new Zend_File_Transfer_Adapter_Http();
                $uploaded_file->addValidator('FilesSize', false, 2000000);
                $uploaded_file->addValidator('Extension', false, array('jpg', 'gif', 'png'));

                //Upload file
                $thumb      = $CFInstance->uploadFile(0, $_FILES['txtfile']['name'], $uploaded_file, dirname(UPLOAD_PATH_CLUB), UPLOAD_PATH_CLUB.'/');

                //Set param insert
                $paramInsert    = array(
                        'userid'        => $this->viewer->userid,
                        'user_type'     => 1,
                        'categoryid'    => $this->categoryConfig['none'],
                        'status'        => 2,
                        'title'         => strip_tags($params['txtTitle']),
                        'content'       => $params['ck_content'],
                        'image'         => !empty($thumb['thumb'])?$thumb['thumb']:'',
                        'url'           => '',
                        'home'          => '',
                        'award'         => '',
                        'info'          => '',
                        'coachman'      => ''
                );

                //Insert
                $articleId  = $CFInstance->insertArticle($paramInsert);

                //Redirect detail page
                if ( $articleId > 0 )
                {
                    $this->_redirect($this->view->MakeUrlSite(1, array('title'=>$paramInsert['title'], 'id'=>$articleId)));
                }
                else
                {
                    //Error
                    $error['code']  = 1;
                    $error['db']    = "Có lỗi xảy ra, vui lòng thực hiện lại sau";

                    //Unlink
                    if ( !empty($thumb['thumb']) )
                    {
                        unlink(dirname(UPLOAD_PATH_CLUB).$thumb['thumb']);
                    }//end if
                }//end if
            }//end if
        }//end if

        //Assign to view
        $this->view->assign('error', $error);
        $this->view->assign('arrPost', $arrPost);

        //Head script
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/ckeditor/ckeditor.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/ckeditor/ckeditor_module.js', 'text/javascript');
        $this->view->headScript()->appendFile(JS_URL_CLUB.'/post-article.js', 'text/javascript');

        //Head title
        $this->view->headTitle('CLB Tôi Yêu - Viết Bài Dự Thi');

        //Head meta data
        $this->view->headMeta()->appendName('description', '“Viết về CLB tôi yêu” là cuộc thi viết về CLB bóng đá bạn yêu thích trên chuyên trang VnExpress, với tổng giá trị giải thưởng lên đến 50 triệu đồng.');
        $this->view->headMeta()->appendName('keywords', 'the thao, cau lac bo, cau lac bo toi yeu, clb toi yeu, toi yeu the thao, cau lac bo toi thich');
    }

    /**
     * Vote action
     */
    public function voteAction()
    {
        //Set no layout & render phtml
        $this->_helper->layout->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);

        //Set response
        $response   = array('error'=>1);

        //Check ajax method
        if ( $this->getRequest()->isXmlHttpRequest() && $this->scheduleOpen && ($this->viewer->userid>0 || isset($_SESSION['userOpenID'])) )
        {
            //Get param
            $arrParam   = $this->getRequest()->getParams();
            //Check param
            if ( isset($arrParam['id']) && is_numeric($arrParam['id']) && $arrParam['id']>0 )
            {
                //User login id
                $userId         = ($this->viewer->userid>0)?$this->viewer->userid:0;

                //Get ClubFavorite instance
                $CFInstance     = ClubFavorite::getInstance();

                //Get article detail
                $articleInfo    = $CFInstance->getArticleDetail($arrParam['id']);

                //Check info for vote
                if ( isset($articleInfo['articleid']) && is_numeric($articleInfo['articleid']) && $articleInfo['articleid']>0 && $articleInfo['categoryid']==$this->categoryConfig['none'] && $articleInfo['status']==1 )
                {
                    //Check user vote
                    if ( $this->viewer->userid > 0 )
                    {
                        $checkVote  = $CFInstance->checkUserVote($articleInfo['articleid'], $userId);
                    }
                    else
                    {
                        $checkVote  = $CFInstance->checkUserVoteByEmail($articleInfo['articleid'], $_SESSION['userOpenID']['email']);
                    }//end if

                    if ( !$checkVote )
                    {
                        //Set param insert
                        $params = array(
                                'articleid'     => $articleInfo['articleid'],
                                'article_type'  => 1,
                                'userid'        => $userId,
                                'ownerid'       => $articleInfo['userid'],
                                'email'         => $this->viewer->userid>0?'':$_SESSION['userOpenID']['email']
                        );
                        //Insert vote
                        $voteId = $CFInstance->insertVote($params);
                        if ( $voteId > 0 )
                        {
                            $response['error']  = 0;
                        }//end if
                    }//end if
                }//end if
            }//end if
        }//end if

        //Echo response
        echo Zend_Json::encode($response);
        exit(1);
    }

    /**
     * Get comment action
     */
    public function getcommentAction()
    {
        //Set no layout & render phtml
        $this->_helper->layout->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);

        //Set response
        $response   = array('error'=>1, 'html'=>'', 'paging'=>'');

        //Check ajax method
        if ( $this->getRequest()->isXmlHttpRequest() )
        {
            //Get param
            $arrParam   = $this->getRequest()->getParams();
            //Check param
            if ( isset($arrParam['id']) && is_numeric($arrParam['id']) && $arrParam['id']>0 )
            {
                //User login id
                $userId         = $this->viewer->userid;

                //Get ClubFavorite instance
                $CFInstance     = ClubFavorite::getInstance();

                //Get article detail
                $articleInfo    = $CFInstance->getArticleDetail($arrParam['id']);

                //Check info for get comment
                if ( isset($articleInfo['articleid']) && is_numeric($articleInfo['articleid']) && $articleInfo['articleid']>0 && $articleInfo['status']==1 )
                {
                    //Set limit, offset, num_link
                    $limit  = 10;
                    $curentPage     = $arrParam['page'];
                    $curentPage     = (is_numeric($curentPage) && $curentPage>0)?$curentPage:1;
                    $offset         = ($curentPage-1)*$limit;
                    $offset         = ($offset>=0)?$offset:0;
                    $num_links      = 5;

                    //Get list comment
                    $listComment    = $CFInstance->getListComment($articleInfo['articleid'], $limit, $offset);
                    if ( !empty($listComment['list']) && is_array($listComment['list']) )
                    {
                        if ( $listComment['total'] > $limit )
                        {
                            $arrOption  = array(
                                    'base_url'      => 'DetailArticle.getComment',
                                    'total_rows'    => $listComment['total'],
                                    'per_page'      => $limit,
                                    'num_links'     => $num_links,
                                    'cur_page'      => $curentPage
                            );
                            $objPaging  = new Util_PaginationAjax($arrOption);
                            $pagingHTML = $objPaging->create_links();
                            $response['paging'] = $pagingHTML;
                        }//end if

                        //Check is admin
                        $session    = Zend_Registry::get('session');
                        $isAdminView    = (isset($session->admin->user->id) && is_numeric($session->admin->user->id) && $session->admin->user->id>0)?true:false;

                        //Assign to view
                        $this->view->assign('listComment', $listComment['list']);
                        $this->view->assign('isAdminView', $isAdminView);

                        //Set response
                        $response['error']  = 0;
                        $response['html']   = trim($this->view->render('box/list_comment.phtml'));
                    }
                }//end if
            }//end if
        }//end if

        //Echo response
        echo Zend_Json::encode($response);
        exit(1);
    }

    /**
     * Comment action
     */
    public function commentAction()
    {
        //Set no layout & render phtml
        $this->_helper->layout->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);

        //Set response
        $response   = array('error'=>1, 'html'=>'');

        //Get current now
        $nowTimestamp   = time();

        //Check time to insert data
        if ( isset($_SESSION['loadTime']) && isset($_SESSION['isLoadFirst']) && ($nowTimestamp-$_SESSION['loadTime'])<10 && $_SESSION['isLoadFirst']==0 )
        {
            $response   = array('error'=>3);
            echo Zend_Json::encode($response);
            exit(1);
        }//end if

        //Set time again
        $_SESSION['loadTime']       = $nowTimestamp;
        $_SESSION['isLoadFirst']    = 0;

        //Check ajax method
        if ( $this->getRequest()->isXmlHttpRequest() )
        {
            //Get param
            $arrParam   = $this->getRequest()->getParams();

            //Proccess data
            $arrParam['content']    = trim(strip_tags($arrParam['content']));
            $arrParam['email']      = trim($arrParam['email']);
            $arrParam['fullname']   = trim(strip_tags($arrParam['fullname']));

            //Validate email
            $validator  = new Zend_Validate_EmailAddress();

            //Check data
            if ( empty($arrParam['content']) || ($this->viewer->userid<=0 && (empty($arrParam['email']) || !$validator->isValid($arrParam['email']) || empty($arrParam['fullname']))) )
            {
                $response   = array('error'=>4);
                echo Zend_Json::encode($response);
                exit(1);
            }//end if

            //Check param
            if ( isset($arrParam['id']) && is_numeric($arrParam['id']) && $arrParam['id']>0 )
            {
                //Get ClubFavorite instance
                $CFInstance     = ClubFavorite::getInstance();

                //Get article detail
                $articleInfo    = $CFInstance->getArticleDetail($arrParam['id']);

                //Check info for comment
                if ( isset($articleInfo['articleid']) && is_numeric($articleInfo['articleid']) && $articleInfo['articleid']>0 && $articleInfo['status']==1 )
                {
                    $arrParam['content']    = Util_Truncate::truncateHTML($arrParam['content'], 1000);

                    //Set param insert
                    if ( $this->viewer->userid > 0 )
                    {
                        $params = array(
                                'userid'    => $this->viewer->userid,
                                'articleid' => $articleInfo['articleid'],
                                'email'     => $arrParam['email'],
                                'fullname'  => $arrParam['fullname'],
                                'website'   => $arrParam['website'],
                                'content'   => $arrParam['content']
                        );
                    }
                    else
                    {
                        $params = array(
                                'userid'    => 0,
                                'articleid' => $articleInfo['articleid'],
                                'email'     => $arrParam['email'],
                                'fullname'  => $arrParam['fullname'],
                                'website'   => $arrParam['website'],
                                'content'   => $arrParam['content']
                        );
                    }//end if

                    //Insert db
                    $commentId = $CFInstance->insertComment($params);
                    if ( $commentId > 0 )
                    {
                        $params['commentid']        = $commentId;
                        $params['creation_time']    = time();
                        $this->view->assign('listComment', array($params));
                        $response['error']  = 0;
                        $response['html']   = trim($this->view->render('box/list_comment.phtml'));
                    }//end if
                }//end if
            }//end if
        }//end if

        //Echo response
        echo Zend_Json::encode($response);
        exit(1);
    }
	
	/**
     * Delete Comment Action
     */
    public function deletecommentAction()
    {
        //Set no layout & render phtml
        $this->_helper->layout->disableLayout(true);
        $this->_helper->viewRenderer->setNoRender(true);

        //Set response
        $response   = array('error'=>1);

        //Check ajax method
        if ( $this->getRequest()->isXmlHttpRequest() )
        {
            //Get param
            $arrParam   = $this->getRequest()->getParams();

            //Check param
            if ( isset($arrParam['id']) && is_numeric($arrParam['id']) && $arrParam['id']>0 && isset($arrParam['commentId']) && is_numeric($arrParam['commentId']) && $arrParam['commentId']>0 )
            {
                //Get ClubFavorite instance
                $CFInstance     = ClubFavorite::getInstance();

                //Get article detail
                $articleInfo    = $CFInstance->getArticleDetail($arrParam['id']);

                //Check info for comment
                if ( isset($articleInfo['articleid']) && is_numeric($articleInfo['articleid']) && $articleInfo['articleid']>0 && $articleInfo['status']==1 )
                {
                    //Check is admin
                    $session    = Zend_Registry::get('session');
                    $permitDel  = false;
                    if ( isset($session->admin->user->id) && is_numeric($session->admin->user->id) && $session->admin->user->id>0 )
                    {
                        $permitDel  = true;
                    }
                    elseif ( $this->viewer->userid > 0 )
                    {
                        $listComment    = $CFInstance->getListComment($articleInfo['articleid'], 0, 0);
                        if ( $listComment['total']>0 && !empty($listComment['list']) && is_array($listComment['list']) )
                        {
                            foreach ( $listComment['list'] as $key=>$row )
                            {
                                if ( $row['commentid']==$arrParam['commentId'] && $row['userid']==$this->viewer->userid )
                                {
                                    $permitDel  = true;
                                    break;
                                }//end if
                            }//end foreach
                        }//end if
                    }//end if

                    //Call delete comment
                    if ( $permitDel )
                    {
                        if ( $CFInstance->deleteComment($arrParam['commentId'], $articleInfo['articleid']) )
                        {
                            $response['error']  = 0;
                        }//end if
                    }//end if
                }//end if
            }//end if
        }//end if

        //Echo response
        echo Zend_Json::encode($response);
        exit(1);
    }

    /**
     * Rule action
     */
    public function ruleAction()
    {
        //Head css
        $this->view->headLink()->appendStylesheet(CSS_URL_CLUB.'/rule.css', 'screen');

        //Check schedule
        if ( !$this->scheduleOpen )
        {
            //Head css
            $this->view->headLink()->appendStylesheet(CSS_URL_CLUB.'/colorbox.css', 'screen');
            $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.colorbox.js', 'text/javascript');
        }//end if

        //Head title
        $this->view->headTitle('CLB Tôi Yêu - Thể Lệ Dự Thi');

        //Head meta data
        $this->view->headMeta()->appendName('description', '“Viết về CLB tôi yêu” là cuộc thi viết về CLB bóng đá bạn yêu thích trên chuyên trang VnExpress, với tổng giá trị giải thưởng lên đến 50 triệu đồng.');
        $this->view->headMeta()->appendName('keywords', 'the thao, cau lac bo, cau lac bo toi yeu, clb toi yeu, toi yeu the thao, cau lac bo toi thich');
    }

    /**
     * Award action
     */
    public function awardAction()
    {
        //Head css
        $this->view->headLink()->appendStylesheet(CSS_URL_CLUB.'/rule.css', 'screen');

        //Check schedule
        if ( !$this->scheduleOpen )
        {
            //Head css
            $this->view->headLink()->appendStylesheet(CSS_URL_CLUB.'/colorbox.css', 'screen');
            $this->view->headScript()->appendFile(JS_URL_CLUB.'/jquery.colorbox.js', 'text/javascript');
        }//end if

        //Head title
        $this->view->headTitle('CLB Tôi Yêu - Giải Thưởng');

        //Head meta data
        $this->view->headMeta()->appendName('description', '“Viết về CLB tôi yêu” là cuộc thi viết về CLB bóng đá bạn yêu thích trên chuyên trang VnExpress, với tổng giá trị giải thưởng lên đến 50 triệu đồng.');
        $this->view->headMeta()->appendName('keywords', 'the thao, cau lac bo, cau lac bo toi yeu, clb toi yeu, toi yeu the thao, cau lac bo toi thich');
    }

    /**
     * Error action
     */
    public function errorAction()
    {
        //Head title
        $this->view->headTitle('CLB Tôi Yêu - Thông Báo Lỗi');

        //Head meta data
        $this->view->headMeta()->appendName('description', '“Viết về CLB tôi yêu” là cuộc thi viết về CLB bóng đá bạn yêu thích trên chuyên trang VnExpress, với tổng giá trị giải thưởng lên đến 50 triệu đồng.');
        $this->view->headMeta()->appendName('keywords', 'the thao, cau lac bo, cau lac bo toi yeu, clb toi yeu, toi yeu the thao, cau lac bo toi thich');
    }
}